package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.dao.RoleDao;
import com.itheima.pojo.Member;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Menu2;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

import java.util.List;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liam
 * @description
 * @date 2020/3/3-17:11
 * @Version 1.0.0
 */
@Service(interfaceClass = MemberService.class)
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;
    @Autowired
    RoleDao roleDao;

    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    @Override
    public Member add(Member member) {
        if (member.getBirthday()==null) {
            String idCard = member.getIdCard();
            DateTime birthday ;
            if (idCard != null) {
                String birthdayStr = idCard.substring(7, 15);
                birthday = DateUtil.parse(birthdayStr, "yyyyMMdd");
            } else {
                birthday=new DateTime();
            }
            member.setBirthday(birthday);
        }
        memberDao.add(member);
        return member;
    }

    @Override
    public List<Map<String, Object>> getMemberSex() {
        return memberDao.getMemberSex1();
    }

    @Override
    public List<Map<String, Object>> getAgeAndNum() {

        return memberDao.getAgeAndNum();
    }

    //根据当前登录的用户id 查询用户的家庭联系人
    @Override
    public List<Member> getFamily(Integer id) {
        List<Member> members = memberDao.findMemberByParentId(id);


        //还可以查询出来自己的信息
       Member member =  memberDao.findMemberById(id);

       members.add(member);
       return members;
    }

    @Override
    public List<Menu2> getMenuList(List<Integer> roleIds) {
        //查询一级菜单
        List<Menu2> roleMuen1 = roleDao.getMenuList(roleIds, 1);
        if (CollectionUtil.isNotEmpty(roleMuen1)) {
            List<Menu2> roleMuen2 = roleDao.getMenuList(roleIds, 2);
            //便利一级菜单
            for (Menu2 menu2 : roleMuen1) {

                int roleMuen1Id = menu2.getId();
                List<Menu2> children = new ArrayList<>();
                for (Menu2 menu21 : roleMuen2) {
                    int parentMenuId = menu21.getParentMenuId();
                    if (roleMuen1Id == parentMenuId) {
                        children.add(menu21);
                    }
                }
                menu2.setChildren(children);
            }

        }

        System.out.println("你行不行哦啊");
        System.out.println("roleMuen1 = " + roleMuen1);
        return roleMuen1;
    }
}
